package com.csdig.cms.service.impl;

import java.io.File;
import java.sql.Timestamp;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.csdig.cms.common.RealPathResolver;
import com.csdig.cms.dao.ContentAttrDAO;
import com.csdig.cms.dao.ContentDAO;
import com.csdig.cms.dao.ContentImgDAO;
import com.csdig.cms.dao.ContentTagDAO;
import com.csdig.cms.dao.ContentTxtDAO;
import com.csdig.cms.model.Channel;
import com.csdig.cms.model.Content;
import com.csdig.cms.model.ContentImg;
import com.csdig.cms.model.ContentTag;
import com.csdig.cms.model.ContentTxt;
import com.csdig.cms.model.ext.ContentExt;
import com.csdig.cms.service.ChannelService;
import com.csdig.cms.service.ContentService;
import com.csdig.cms.utils.FrontUtils;
import com.csdig.cms.utils.PageUtils;
import com.csdig.db.DBUtils;
import com.csdig.db.model.Pagination;

@Service
@Transactional
public class ContentServiceImpl implements ContentService {

	@Autowired
	private ContentDAO contentDao;

	@Autowired
	private ContentTxtDAO contentTxtDao;

	@Autowired
	private ContentAttrDAO contentAttrDao;

	@Autowired
	private ContentTagDAO contentTagDao;

	@Autowired
	private ChannelService channelService;

	@Autowired
	private ContentImgDAO imgDao;

	@Autowired
	private RealPathResolver pathResolver;

	@Override
	public Pagination<Content> findAllByPid(Integer channelPid, int pageNo, int pageSize) throws Exception {
		if (channelPid == null) {
			channelPid = -1;
		}
		List<Integer> list = channelService.getNestChannelIdsByPid(channelPid, true);
		if (list == null || list.size() == 0) {
			return new Pagination<Content>();
		}
		return contentDao.findByCondition(list, pageNo, pageSize);
	}

	@Override
	public Integer saveContent(Content bean, String content) throws Exception {
		Integer channelId = bean.getChannelId();
		Channel channel = channelService.getById(channelId);

		String des = bean.getDescription();
		bean.setDescription(PageUtils.getDes(des));
		bean.setReleaseDate(new Timestamp(System.currentTimeMillis()));

		if (channel.getIsSingle()) {
			bean.setLink(channel.getChannelPath());
		} else {
			bean.setLink(PageUtils.generatePageLink());
		}

		contentDao.add(bean);
		ContentTxt txt = new ContentTxt();
		txt.setContentId(DBUtils.getLastInsertID().intValue());
		txt.setTxt(content);
		contentTxtDao.add(txt);
		return txt.getContentId();
	}

	@Override
	public Content findById(Integer id) throws Exception {
		return contentDao.findById(id);
	}

	@Override
	public ContentTxt findTxtById(Integer id) throws Exception {
		return contentTxtDao.findbyContentId(id);
	}

	@Override
	public void updateContent(Content bean, String content) throws Exception {
		Content oldBean = findById(bean.getContentId());
		oldBean.setTitle(bean.getTitle());
		oldBean.setDescription(PageUtils.getDes(bean.getDescription()));
        oldBean.setTitleImg(bean.getTitleImg());
		contentDao.update(oldBean);

		ContentTxt txt = findTxtById(bean.getContentId());
		txt.setTxt(content);
		contentTxtDao.update(txt);
	}

	@Override
	public void del(Integer contentId) throws Exception {
		Content contentVO = findById(contentId);
		delContentImg(contentVO.getContentId());
		contentTxtDao.delete(contentVO.getContentId());
		contentAttrDao.delete(contentVO.getContentId());
		contentTagDao.delete(contentVO.getContentId());
		contentDao.delete(contentVO.getContentId());
	}

	private void delContentImg(Integer contentId) throws Exception {
		String domain = FrontUtils.getDomain();
		List<ContentImg> list = imgDao.findByContentId(contentId);
		if (list != null && list.size() > 0) {
			for (ContentImg img : list) {
				String path = "";
				String url = img.getImgUrl();
				if (StringUtils.isNotEmpty(domain) && url.startsWith(domain)) {
					path = url.substring(url.indexOf(domain) + domain.length());
				} else {
					path = url;
				}
				String filePath = pathResolver.get(path);
				File f = new File(filePath);
				if (f.exists())
					f.delete();
			}
		}

	}

	public static void main(String[] args) {
		String url = "http://www.tucaobj.com/r/upload/2014-07-11/5.jpg";
		String domain = "http://www.tucaobj.com";
		System.out.println(url.substring(url.indexOf(domain) + domain.length()));
	}

	@Override
	public Content findByPath(String path) throws Exception {
		List<Content> list = contentDao.findByCondition(new String[] { "link" }, new Object[] { path });
		if (list != null && list.size() > 0) {
			Content content = list.get(0);

			ContentTxt txt = contentTxtDao.findbyContentId(content.getContentId());
			content.setTxt(txt);

			List<ContentTag> tags = contentTagDao.findByCondition(new String[] { "content_id" },
					new Object[] { content.getContentId() });
			content.setTagList(tags);

			return content;
		}
		return null;
	}

	// 排除单页
	@Override
	public List<ContentExt> getListByIdsForTag(Integer channelIds, int first, int count, String orderBy)
			throws Exception {
		if (channelIds == null) {
			channelIds = Integer.valueOf(-1);
		}
		return contentDao.findListForTag(channelIds, first, count, orderBy);
	}

	@Override
	public Pagination<ContentExt> getPagByIdsForTag(Integer channelIds,  int pageNo, String orderBy)
			throws Exception {
		if (channelIds == null) {
			channelIds = Integer.valueOf(-1);
		}
		return contentDao.findPagForTag(channelIds, pageNo, Pagination.DEF_COUNT, orderBy);
	}
}
